<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class Response
{
    //所有外部的三方回调,都应添加路由过滤,自定义响应格式
    protected $except = [
        '/callback/*',
        '*telescope*',
    ];

    public function handle(Request $request, Closure $next)
    {
        /**
         * @var JsonResponse $response
         */
        $response = $next($request);

        if ($this->inExceptArray($request)) {
            return $response;
        }

        if ($response instanceof JsonResponse) {
            $data = [
                'code' => 1,
                'message' => 'SUCCESS',
                'data' => $response->getData(),
            ];
            $response->setData($data)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }

        return $response;
    }

    protected function inExceptArray(Request $request): bool
    {
        foreach ($this->except as $except) {
            if (Str::is($except, $request->getRequestUri())) {
                return true;
            }
        }

        return false;
    }
}
